<?php
/*                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                            O\ = /O
 *                        ____/`---'\____
 *                      .   ' \\| |// `.
 *                       / \\||| : |||// \
 *                     / _||||| -:- |||||- \
 *                       | | \\\ - /// | |
 *                     | \_| ''\---/'' | |
 *                      \ .-\__ `-` ___/-. /
 *                   ___`. .' /--.--\ `. . __
 *                ."" '< `.___\_<|>_/___.' >'"".
 *               | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *                 \ \ `-. \_ __\ /__ _/ .-` / /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *
 *         .............................................
 *                  佛祖保佑             永无BUG
 *
 * ======================================================
 * @author: Ethan Lu <ethan.lu@qq.com>
 * 
 */

namespace frontend\components\sms;

use yii\base\Action;
use yii\base\Exception;

class SmsAction extends Action
{
    const MOBILE_GET_VAR = 'mobile';

    public $options;

    public $prefix;

    public $template;

    public $params = '{code}';

    public function run()
    {
        if(!isset($this->options)) {
            throw new Exception('短信通道未配置', 500);
        }
        $mobile = \Yii::$app->request->getQueryParam(self::MOBILE_GET_VAR);

        if($mobile !== null) {

            if(\Yii::$app->cache->get('count_'.$mobile) >= 3) {
                return json_encode(['status' => 0, 'msg' => '每天只能发送3次短信验证码']);
            }

            $cache = \Yii::$app->cache->get($mobile);
            if($cache === false) {
                return $this->ucpaas($mobile);
            }
            return json_encode(['status' => 0, 'msg' => '120秒后再重新发送', 'return' => time() - $cache]);
        }
    }

    protected function ucpaas($mobile)
    {
        $sms = new Ucpaas($this->options);
        $code = mt_rand(1000, 9999);
        \Yii::$app->session->set('code_'.$mobile, $code, 600);
        \Yii::$app->cache->set($mobile, time(), 120);


        $count = \Yii::$app->cache->get('count_'.$mobile) === false ? 1: (int)\Yii::$app->cache->get('count_'.$mobile) + 1;
        \Yii::$app->cache->set('count_'.$mobile, intval($count) + 1, strtotime(date('Y-m-d 00:00:00', strtotime('+1 day'))) - time());


        $ret = $sms->templateSMS($this->options['appId'], $mobile, $this->options['templateId'], str_replace('{code}', $code, $this->params));
        $retRes = json_decode($ret);
        $status = $retRes->resp->respCode == '000000' ? 1 : 0;
        return json_encode([
            'status' => $status,
            'msg' => $status ? '发送成功!' : '发送失败!',
        ]);
    }

}